package com.qianniu.napi.admin.service.akka;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class UserActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger(UserActor.class);

    private IActgxService actgxService = (IActgxService) SpringUtil.getBean("actgxServiceImpl");
    private IUserService userService = (IUserService) SpringUtil.getBean("userServiceImpl");
    private IUsermpService usermpService = (IUsermpService) SpringUtil.getBean("usermpServiceImpl");
    private IFensService fensService = (IFensService) SpringUtil.getBean("fensServiceImpl");
    private IFenxiaoService fenxiaoService = (IFenxiaoService) SpringUtil.getBean("fenxiaoServiceImpl");
    private IRedisService redisService = (IRedisService) SpringUtil.getBean("redisServiceImpl");
    private IUserstatService userstatService = (IUserstatService) SpringUtil.getBean("userstatServiceImpl");
    private IShareOpenService shareOpenService = (IShareOpenService) SpringUtil.getBean("shareOpenServiceImpl");
    private IJifenService jifenService = (IJifenService) SpringUtil.getBean("jifenServiceImpl");
    private IAccountService accountService = (IAccountService) SpringUtil.getBean("accountServiceImpl");
    private IXnbiService xnbiService = (IXnbiService) SpringUtil.getBean("xnbiServiceImpl");
    private IJifenFlowService jifenFlowService = (IJifenFlowService) SpringUtil.getBean("jifenFlowServiceImpl");
    private IMerchantConfigService merchantConfigService = (IMerchantConfigService) SpringUtil.getBean("merchantConfigServiceImpl");

//    private IUserstatService userstatService = (IUserstatService) SpringUtil.getBean("IUserstatService");
//    private String[] names = SpringUtil.getApplicationContext().getBeanDefinitionNames();
//    private String[] aliass = SpringUtil.getApplicationContext().getAliases("IUserService");

    @Override
    public void onReceive(Object message) {
        logger.info(">>>>>>UserActor in");

        if (message instanceof String) {
            String msg = message.toString();
            logger.info(">>>>>>UserActor receive message:" + msg);

            // 格式 type+uid+toke
            String[] arr = msg.split("@");
            logger.info(">>>>>>receive arr.length:" + arr.length);
//            if (arr.length < 3) return;

            String type = arr[0];
            String ywid = arr[1];
//            String wxType = arr[2];
            String exta = null;

            switch (type) {
                case Constants.AKKA_MSG_CUSERSTAT:
                    createUserstat(ywid);
                    break;
                case Constants.AKKA_MSG_ACCESS_USERSTAT:
                    //accessUserstat(ywid);
                    break;
                case Constants.AKKA_MSG_VISIT_USERSTAT:
                    visitUserstat(ywid);
                    break;
                case Constants.AKKA_MSG_FENXIAO_ORI:
                    exta = arr[2];
                    fenxiaoOri(ywid, exta);
                    break;
                case Constants.AKKA_MSG_FENXIAO_SCENE:
                    exta = arr[2];
                    fenxiaoScene(ywid, exta);
                    break;
                case Constants.AKKA_USER_CREATE_AVATOR:
                    copytouxiang(ywid);
                    break;
                case Constants.AKKA_MSG_SHARE_OPEN:
                    //fensiProcess(ywid);
                    //jiangliProcess(ywid);
                    break;
                case Constants.AKKA_FENSI_HIGH_PROCESS:
                    exta = arr[2];
                    fensiProcess(ywid, exta);
                    break;
                case Constants.AKKA_HUIYUAN_TUIJIAN_SHENGJI:
//                    copytouxiang(ywid);
                    break;
                default:
                    return;
            }
        }
    }

    // 实时生成图片
    private void createUserstat(String uid) {
        logger.info(">>>>>> createUserstat in");

        Wrapper<User> entity = new EntityWrapper<User>().setSqlSelect("id,name,guid,mid,mpid").eq("id", uid);
        User user = userService.selectOne(entity);

        Userstat ustat = new Userstat();
        ustat.setUid(user.getId());
        ustat.setGuid(user.getGuid());
        ustat.setMid(user.getMid());
        ustat.setMpid(ObjectUtil.getMpid());

        ustat.setAccess(0);
        ustat.setVisit(0);

        ustat.setAccessc(0);
        ustat.setVisitc(0);

        ustat.setGfav(0);
        ustat.setUfav(0);
        ustat.setZuan(0);

        ustat.setKehu(0);
        ustat.setShare(0);
        ustat.setCall(0);
        ustat.setShuo(0);
        ustat.setDongtai(0);

        ustat.setKehu(0);
        ustat.setRenqi(1);
        ustat.setState(1);
        ustat.setIsHuoyue(1);
        ustat.setLastvtime(new Date());
        ustat.setCreatetime(new Date());

        logger.info(">>>>>>ustat.insert");
        ustat.insert();
    }

    // 朋友圈分享
    private void fenxiaoScene(String ywid, String exta) {
        logger.info("----------------------------------------------------------------------------fenxiaoScene come in");

        logger.info(">>>>>> fenxiaoScene in ywid=" + ywid);
        logger.info(">>>>>> fenxiaoScene in exta=" + exta);
        String[] arr = ywid.split("_");
        logger.info(">>>>>>receive arr.length:" + arr.length);
        if (arr.length < 3) return;

        String puid = arr[0];

        // =====待完善【缺少奖励逻辑】
        User cuser = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,nick_name nickName,avatar_pic avatarPic,mid,mpid").eq("id", exta));

        logger.debug("====cuser=" + JSON.toJSONString(cuser));
        if (cuser == null) return;

        int count = fensService.selectCount(new EntityWrapper<Fens>()
                .eq("uid", cuser.getId()).eq("puid", puid));
        Fens fens = new Fens();
        if (count == 0) {

            fens.setUid(cuser.getId());
            fens.setGuid(cuser.getGuid());

            fens.setNickname(cuser.getNickName());
            fens.setAvatarpic(cuser.getAvatarPic());
            fens.setPuid(Long.valueOf(puid));
            //===待完善
//          fens.setPguid(Long.valueOf(pguid));

            fens.setLevelType(1);
            fens.setStatus(1);
            fens.setState(1);
            fens.setOriginType(1);//转发
            fens.setPage(arr[1]);//转发页
            fens.setAct(arr[2]);//转发页

            if (arr.length > 3) fens.setYwid(arr[3]);
            fens.setMid(cuser.getMid());
            fens.setMpid(cuser.getMpid());
            fens.setCreatetime(new Date());
            fens.insert();

            logger.debug("--------------------------------------1th fensi insert OK");
        }

        // =================新用户注册奖励=================
        nuserFan(Long.valueOf(puid), cuser.getMpid());

        // 处理二级粉丝
        // ===待完善，多级粉丝，多级会员【会员之间不能断层】
        // 1、多级分销
        // 2、分销级别大于1
        // 3、分享用户必须是会员
        // 普通用户没有多级粉丝功能，会员用户才能有
        MerchantConfig mconfig = redisService.getMconfig(fens.getMpid());
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", cuser.getMpid()));
        if (mconfig.getIsFenxiao() == 1
                && fenxiao != null && fenxiao.getFxlevel() > 1) {
            highfens(fens, fenxiao.getFxlevel());
        }


    }

    // 页面转发
    private void fenxiaoOri(String ywid, String uid) {
        logger.info("---------------------------------------------------------------------------------------------fenxiaoOri come in");
        logger.info(">>>>>> fenxiaoOri in ywid=" + ywid);
        logger.info(">>>>>> fenxiaoOri in uid=" + uid);
        String[] arr = ywid.split("_");
        logger.info(">>>>>>receive arr.length:" + arr.length);
        if (arr.length < 3) return;

        String guid = arr[0];
        User puser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,nick_name nickName,avatar_pic avatarPic,is_member isMember," +
                "member_level memberLevel,is_mch isMch,is_platform isPlatform,is_agent isAgent,mid,mpid,guid")
                .eq("guid", guid));

        User cuser = userService.selectById(uid);
        logger.debug("--------------------------------------------------------puser=" + JSON.toJSONString(puser));
        logger.debug("----------------------------------------------------------cuser=" + JSON.toJSONString(cuser));
        if (puser == null || cuser == null) return;

        int count = fensService.selectCount(new EntityWrapper<Fens>().eq("uid", cuser.getId())
                .eq("state", 1)
                .eq("level_type", 1)
                .eq("puid", puser.getId()));
        Fens fens = new Fens();
        logger.debug("----------------------------------------------------------count=" + count);
        if (count == 0) {

            fens.setUid(cuser.getId());
            fens.setNickname(cuser.getNickName());
            fens.setAvatarpic(cuser.getAvatarPic());
            fens.setPuid(puser.getId());
            fens.setPguid(puser.getGuid());

            fens.setLevelType(1);
            fens.setStatus(1);
            fens.setState(1);
            fens.setOriginType(1);//转发

            fens.setPage(arr[1]);//转发页
            fens.setAct(arr[2]);//转发页
            if (arr.length > 3) fens.setYwid(arr[3]);

            fens.setMid(cuser.getMid());
            fens.setMpid(cuser.getMpid());
            fens.setCreatetime(new Date());
            fens.insert();
            logger.debug("-----------------------------------------------------------1th fensi insert OK");
        }

        // =================拉新用户注册奖励=================
        // ================拉新用户默认一级粉丝直接奖励，奖励给上一级=================
        nuserFan(puser.getId(), puser.getMpid());

        // 多级分销多级处理
        MerchantConfig mconfig = redisService.getMconfig(cuser.getMpid());
        if (mconfig.getIsFenxiao() != null & mconfig.getIsFenxiao() == 1
                && mconfig.getFslevel() != null & mconfig.getFslevel() > 1) {
            logger.debug("------------------------------------------fenxiaoOri fensi to highfens mconfig.getFslevel()=" + mconfig.getFslevel());
            highfens(fens, mconfig.getFslevel());
        }
    }

    //拉新用户推荐奖励(奖励上一级用户)
    private void nuserFan(Long uid, Long mpid) {

        logger.info("-------------------------------------------nuserFan come in");
        FanConfig fconfig = redisService.getFanconfig(mpid);
        if (fconfig == null) {
            logger.error("--------------------------------------nuserFan mconfig=null");
            return;
        }

        BigDecimal fan = fconfig.getNuserfanMount();
        Integer type = fconfig.getNuserfanType();
        if (type == null || type == 0) {
            logger.info("---------------------------------------------------------------------registFan type=" + type);
            return;
        }

        User puser = userService.selectById(uid);
        if (puser == null) {
            logger.error("--------------------------------------nuserFan puser=null");
            return;
        }

        if (type.intValue() == XffanType.jifen.getVal()) {

            jifenService.addJifenFlow(uid, puser.getMid(), mpid,
                    fan, true, FantimeType.now.getVal(),
                    StringUtil.getSnNo("JF"), IotypeEnum.input, JftypeEnum.share, "", 0l);
        } else if (type.intValue() == XffanType.xnbi.getVal()) {

            xnbiService.addXnbiFlow(uid, puser.getMid(), mpid,
                    fan, true, FantimeType.now.getVal(),
                    StringUtil.getSnNo("BI"), IotypeEnum.input, JftypeEnum.share, "", 0l);
        } else if (type.intValue() == XffanType.qian.getVal()) {

            accountService.addAccountFlow(uid, puser.getMid(), mpid,
                    fan, true, FantimeType.now.getVal(),
                    StringUtil.getSnNo("ACT"), IotypeEnum.input, XftypeEnum.xffanli, "", 0l);
        }

    }

    // 我访问的
    private void visitUserstat(String ywid) {
        logger.info(">>>>>> accessUserstat in ywid=" + ywid);
        String[] arr = ywid.split("##");
//            recordAct(Long uid, Long vuid, Long mid, Long mpid, int type +"_"+ip+"_"+os;);

        logger.info(">>>>>>receive arr.length:" + arr.length);
//            if (arr.length < 3) return;

        Long uid = 0l;
        Long vuid = 0l;
        Long mid = 0l;
        Long mpid = 0l;

        try {
            uid = Long.parseLong(arr[0]);
            vuid = Long.parseLong(arr[1]);
            mid = Long.parseLong(arr[2]);
            mpid = Long.parseLong(arr[3]);
        } catch (Exception e) {
        }

        int type = 1;
        try {
            type = Integer.parseInt(arr[4]);
        } catch (Exception e) {

        }
        String ip = arr[5];
        String os = arr[6];

        this.recordAct(uid, vuid, mid, mpid, type, ip, os);
    }

    // 记录当前用户的行为
    public void recordAct(Long uid, Long vuid, Long mid, Long mpid, int type, String ip, String os) {

        Wrapper<Actgx> aentity = new EntityWrapper<Actgx>().setSqlSelect("id,uid,type,renqi").eq("type", type)
                .eq("uid", uid).eq("vuid", vuid).eq("isfirst", 1);
        int ucout = actgxService.selectCount(aentity);

        int vcout = 1;
        Actgx act = new Actgx();
        if (type == ActgxType.visit.getVal()) {
            Wrapper<Actgx> ventity = new EntityWrapper<Actgx>().setSqlSelect("id,uid,type,renqi").eq("type", type)
                    .eq("uid", vuid).eq("vuid", uid).eq("isfirst", 1);
            List<Actgx> actgxs = actgxService.selectList(ventity);
            vcout = actgxs == null || actgxs.size() == 0 ? 0 : actgxs.size();
//            if(vcout>0) act = actgxs.get(0);
        }
        //查询人气
        Wrapper<Userstat> raentity = new EntityWrapper<Userstat>().setSqlSelect("id,uid,renqi").eq("uid", vuid);
        Userstat ractgx = userstatService.selectOne(raentity);
        int renqi = 1;
        if (ractgx != null && ractgx.getRenqi() != null) {
            renqi = ractgx.getRenqi() + 1;
        }

        //查询user人气
        Wrapper<Usermp> entity = new EntityWrapper<Usermp>()
                .setSqlSelect("id,name,company,gs,phone,duty,hasmp,gongkai,avatar_pic avatarPic,nick_name nickName,hangye,weixin,photo,guid")
                .eq("state", 1).eq("id", vuid);
        Usermp user = usermpService.selectOne(entity);

        act.setUid(uid);
        act.setVuid(vuid);

        act.setMid(mid);
        act.setQqcount(0);
        act.setMpid(mpid);
        act.setCreatetime(new Date());
        act.setType(type);
        act.setIp(ip);
        act.setRenqi(renqi);
        act.setIsfirst(vcout == 0 ? 1 : 0);
        act.setTerminal(os);

        if (ractgx != null) {
            Actgx empty = new Actgx();
            empty.setUid(uid);
            empty.setRenqi(renqi);

            Wrapper<Actgx> update = new EntityWrapper<Actgx>().ge("type", 3).or()
                    .le("type", 5).ne("type", 4).eq("uid", uid);
            actgxService.update(empty, update);
        }

        act.setName(Strings.isNullOrEmpty(user.getName()) ? user.getNickName() : user.getName());
        act.setAvatar(Strings.isNullOrEmpty(user.getPhoto()) ? user.getAvatarPic() : user.getPhoto());
        act.setPhone(user.getPhone());
        act.setCompany(user.getCompany());
        act.setGs(user.getGs());
        act.setGuid(user.getGuid());
        act.setHangye(user.getHangye());
        if (type != 3 && type != 4) act.insert();

        Wrapper<Userstat> uentity = new EntityWrapper<Userstat>().eq("uid", uid);
        Userstat ustat = userstatService.selectOne(uentity);

        Wrapper<Userstat> ventity = new EntityWrapper<Userstat>().eq("uid", vuid);
        Userstat vstat = userstatService.selectOne(ventity);

        logger.debug("=========ustat=" + JSON.toJSONString(ustat));
        logger.debug("=========vstat=" + JSON.toJSONString(vstat));

        if (ustat == null) {
            this.initUstat(vuid, vstat, user.getGuid(), mid, mpid, type);
        } else {
            this.updateUstat(ustat, vstat, type, ucout, vcout);
        }
    }

    // 被访问用户的行为数据统计
    private Userstat initUstat(Long vuid, Userstat vstat, String guid, Long mid, Long mpid, int type) {

        Userstat ustat = new Userstat();
        ustat.setUid(vuid);
        ustat.setGuid(guid);
        ustat.setMid(mid);
        ustat.setMpid(mpid);

        ustat.setAccess(type == ActgxType.access.getVal() ? 1 : 0);
        ustat.setVisit(type == ActgxType.visit.getVal() ? 1 : 0);

        ustat.setAccessc(type == ActgxType.access.getVal() ? 1 : 0);
        ustat.setVisitc(type == ActgxType.visit.getVal() ? 1 : 0);

        ustat.setGfav(type == ActgxType.gfav.getVal() ? 1 : 0);
        ustat.setUfav(type == ActgxType.ufav.getVal() ? 1 : 0);
        ustat.setZuan(type == ActgxType.dianzan.getVal() ? 1 : 0);

        ustat.setKehu(type == ActgxType.addkehu.getVal() ? 1 : 0);

        ustat.setKehu(type == ActgxType.share.getVal() ? 1 : 0);
        ustat.setShare(type == ActgxType.share.getVal() ? 1 : 0);
        ustat.setCall(type == ActgxType.call.getVal() ? 1 : 0);

        ustat.setShuo(0);
        ustat.setDongtai(0);
        ustat.setKehu(0);
        ustat.setRenqi(1);
        ustat.setState(1);
        ustat.setIsHuoyue(1);
        ustat.setLastvtime(new Date());
        ustat.setCreatetime(new Date());
        ustat.insert();

        if (type == ActgxType.visit.getVal()) {
            vstat.setAccess(vstat.getAccessc() + 1);
            vstat.setAccessc(vstat.getAccessc() + 1);
            vstat.updateById();
        }

        return ustat;
    }

    private void updateUstat(Userstat ustat, Userstat vstat, int type, int cout, int vcout) {
        logger.debug("=========updateUstat type=" + type);
        logger.debug("=========updateUstat ustat=" + JSON.toJSONString(ustat));
        cout = cout == 0 ? 1 : 0;
        ustat.setModifytime(new Date());
        vstat.setModifytime(new Date());
        vstat.setRenqi(vstat.getRenqi() + 1);// 任何操作，对方人气+1

        if (type == ActgxType.access.getVal()) {
            ustat.setAccess(ustat.getAccess() + cout);//人数
            ustat.setAccessc(ustat.getAccessc() + 1);//次数
        } else if (type == ActgxType.visit.getVal()) {
            ustat.setVisit(ustat.getVisit() + cout);//人数
            ustat.setVisitc(ustat.getVisitc() + 1);//次数

            vstat.setAccess(vstat.getAccess() + cout);
            vstat.setAccessc(vstat.getAccessc() + 1);

            userstatService.update(ustat, new EntityWrapper<Userstat>().eq("id", ustat.getId()));
            vstat.updateById();

        } else if (type == ActgxType.gfav.getVal()) {
            ustat.setGfav(ustat.getGfav() + cout);

        } else if (type == ActgxType.ufav.getVal()) {
            ustat.setUfav(ustat.getUfav() + cout);

        } else if (type == ActgxType.dianzan.getVal()) {
            vstat.setZuan(ustat.getZuan() + 1);

        } else if (type == ActgxType.addkehu.getVal()) {
            ustat.setKehu(ustat.getKehu() + cout);
            userstatService.update(ustat, new EntityWrapper<Userstat>().eq("id", ustat.getId()));

        } else if (type == ActgxType.share.getVal()) {

            vstat.setShare(ustat.getShare() + 1);
        } else if (type == ActgxType.call.getVal()) {


            vstat.setCall(ustat.getCall() + 1);
        }

        vstat.updateById();
        logger.debug("=========updateUstat 111");
        logger.debug("=========updateUstat updateById ok");

//        return ustat;
    }

    // 打开小程序onLaunch事件触发粉丝数据处理
    // 此时不绑定上下级粉丝关系【该动作尽在用户登录的时候绑定】
    private void fensiProcess(String ywid) {
        ShareOpen shareOpen = shareOpenService.selectById(ywid);
        if (shareOpen == null || shareOpen.getUid() == null) return;

        List<Fens> fenslist = fensService.selectList(new EntityWrapper<Fens>()
                .eq("uid", shareOpen.getUid())
                .le("level_type", 1));

        if (fenslist.size() > 0) {
            logger.debug("--------------------------------------fensi data exist");
            return;
        }
        logger.debug("--------------------------------------fensiProcess 1111");
        // 分享者登陆成功的用户才算粉丝，未登陆统统算游客，游客不计入粉丝库
        // 锁客模式下，记入粉丝数据
        MerchantConfig mconfig = redisService.getMconfig(shareOpen.getMpid());
        if (mconfig.getIsSuofen() != 1) {
            logger.debug("--------------------------------------fensiProcess mconfig.getIsSuofen()=" + mconfig.getIsSuofen());
            return;
        }

        // 分享者如果未登陆无用户数据,游客不计入粉丝库
        User puser = redisService.getUserByGuid(shareOpen.getZguid());
        if (puser == null) {
            logger.debug("--------------------------------------fensiProcess puser=null");
            return;
        }

        User user = redisService.getUserByGuid(shareOpen.getGuid());

        Fens fens = new Fens();
        fens.setMid(shareOpen.getMid());
        fens.setMpid(shareOpen.getMpid());
        fens.setGuid(shareOpen.getGuid());

        if (user != null) {
            fens.setUid(user.getId());
            fens.setNickname(user.getNickName());
            fens.setAvatarpic(user.getAvatarPic());
        }
        fens.setPuid(puser.getId());
        fens.setPguid(puser.getGuid());

        //===待完善
        fens.setLevelType(1);
        fens.setStatus(1);
        fens.setState(1);

        fens.setOriginType(1);//分享转发【不是分享转发，则没有上下级关系】
        fens.setPage(shareOpen.getPath());//转发页
        fens.setAct("menu");//转发页
        fens.setCreatetime(new Date());
        fens.insert();

        logger.debug("--------------------------------------fensiProcess 222222");

        // 多级分销多级处理
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid", shareOpen.getMpid())
        );
        logger.debug("--------------------------------------fensiProcess 222222 fenxiao=" + fenxiao);
        if (mconfig.getIsFenxiao() == 1
                && mconfig.getFslevel() != null && mconfig.getFslevel() > 1) {
            logger.debug("--------------------------------------fensiProcess 33333");
            highfens(fens, fenxiao.getFxlevel());
        }
    }


    // 打开小程序onLaunch事件触发粉丝数据处理
    private void fensiProcess(String uid, String puid) {

        Fens fens = fensService.selectOne(new EntityWrapper<Fens>().eq("uid", uid).eq("puid", puid));
        if (fens == null) return;

        logger.debug("--------------------------------------fensiProcess 222222");

        // 多级分销多级处理
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid", fens.getMpid()));
        logger.debug("--------------------------------------fensiProcess 222222 fenxiao=" + fenxiao);
        MerchantConfig mconfig = redisService.getMconfig();

        if (mconfig.getIsFenxiao() == 1
                && mconfig.getFslevel() != null && mconfig.getFslevel() > 1) {
            logger.debug("----------------------------------fensiProcess 33333");
            highfens(fens, fenxiao.getFxlevel());
        } else {
            logger.debug("----------------------------------fenxiao is not config right for mpid=" + fens.getMpid());
        }
    }

    private void highfens(Fens fens, int fxlevel) {
        //  处理二级粉丝
        // ===待完善，多级粉丝，多级会员【会员之间不能断层】
        Long puid = fens.getPuid();
        // 通过上一级用户的粉丝链来维护处理
        logger.debug("--------------------------------------highfens puid=" + puid);
        for (int m = 2; m <= fxlevel; m++) {

            //上一级必须注册切用户存在&&并且是会员,粉丝资源只给代理权限的人
            //中间不能断层
            //fens.getPuid() 可能为空

            User puser = userService.selectById(puid);
            //用户会员+商家
//            if (puser == null || (puser.getIsMember()!=1 && puser.getIsAgent() != 1)) {
            if (puser == null) {
                logger.debug("-------------------highfens puser==null||puser.getMemberLevel()==0");
                break;
            }

            // 查找上一级粉丝对象，并关联【当前级---爷爷级】关系
            Fens pfens = fensService.selectOne(new EntityWrapper<Fens>()
                    .setSqlSelect("id,puid,pguid")
                    .eq("level_type", m - 1)
                    .eq("uid", puid)
                    .eq("state", 1)
                    .orderBy("status", false));

            if (pfens == null) {
                logger.debug("-------------------highfens pfens=null");
                break;
            }

            // 上上级用户（祖父级）
            User yyuser = userService.selectById(pfens.getPuid());
            // 上级为空+不是会员|代理，不开通多级粉丝功能
            // 粉丝资源只给代理权限的人 (终端会员 + 代理人)
            boolean agent = yyuser != null && (yyuser.getIsMember() == 1 || yyuser.getIsAgent() == 1);

            if (yyuser == null || !agent) {
                logger.debug("========================highfens() yyuser=" + yyuser);
                break;
            }

            if (pfens != null && pfens.getPuid() != null) {
                int count = fensService.selectCount(new EntityWrapper<Fens>()
                        .eq("guid", fens.getGuid())
                        .eq("puid", pfens.getPuid()));
                if (count > 0) continue;

                fens.setId(null);
                fens.setPuid(yyuser.getId());
                fens.setPguid(yyuser.getGuid());
                fens.setLevelType(m);

                fens.insert();
                logger.debug("-------------------------------------" + m + "th fensi insert OK");
            }
        }
    }

    // 实时生成图片
    private void copytouxiang(String uid) {

        Wrapper<User> entity = new EntityWrapper<User>().setSqlSelect("id,name,mpid,avatar_pic avatarPic").eq("id", uid);
        User user = userService.selectOne(entity);
        MerchantApp mapp = redisService.getMApp(user.getMpid());
        String mcode = mapp.getMcode() + "/" + mapp.getMpcode() + "/0avatar/";
        logger.info("==============================copytouxiang 22221111");

        String uppath = mapp.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
        logger.info("==============================copytouxiang 22222222");

        uppath = uppath + mcode;
        String host = mapp.getIscdn().intValue() == 1 ? Constants.IMG_UPLOAD_HOST.replace("img.", "imgcdn.") : Constants.IMG_UPLOAD_HOST;

        logger.info("==============================userTouxiangCdn uppath=" + uppath);
        HttpUtil.checkDirectory(uppath);
        logger.info("==============================userTouxiangCdn 22223333");

        String ul = user.getAvatarPic();
        if (Strings.isNullOrEmpty(ul)) return;

        String imgname = EncryptUtil.md5(ul) + ".jpg";
        String txpath = uppath + imgname;

        if (!HttpUtil.downloadFile(ul, txpath)) {
            logger.info("==============================copytouxiang download failed and retry");
            // 头像,异步创建用户统计信息
            AkkaServer.system.actorOf(Props.create(UserActor.class))
                    .tell(Constants.AKKA_USER_CREATE_AVATOR + "@" + uid, ActorRef.noSender());
            return;
        }
        logger.info("==============================userTouxiangCdn  111 txpath=" + txpath);

        txpath = mapp.getIscdn() == 1 ? txpath.replace(Constants.IMG_UPLOAD_PATH + "0cdn/", Constants.IMG_UPLOAD_HOST.replace("img.", "imgcdn.")) : txpath.replace(Constants.IMG_UPLOAD_PATH, Constants.IMG_UPLOAD_HOST);
        logger.info("==============================userTouxiangCdn 222 txpath=" + txpath);

        user.setAvatarPic(txpath);
        user.updateById();

        redisService.delUser(user.getId());

        logger.info("==============================copytouxiang OK");
    }

}
